package com.dragon.linkedlist;

import java.util.List;

/**
 * @author dragon
 * @version 1.0
 * @description
 * @date created in 2018-12-17
 */
public class LeetCodeLinkedListSolution {

    /**
     * 定义一个单链表
     */
    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    /**
     * 删除元素
     *
     * @param head
     * @param val
     * @return
     */
    public ListNode removeElements(ListNode head, int val) {
        //1.删除头节点
        while (head != null && head.val == val) {
            ListNode delNode = head;
            head = delNode.next;
            delNode.next = null;
        }
        if (head == null) {
            return null;
        }
        //2.删除非头节点
        ListNode prev = head;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            } else {
                prev = prev.next;
            }
        }
        return head;
    }

}

